package com.team.six.bluecatshop.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.team.six.bluecatshop.domain.Activity;
import com.team.six.bluecatshop.domain.ActivityExample;
import com.team.six.bluecatshop.domain.Product;
import com.team.six.bluecatshop.domain.SeachActivityReponse;
import com.team.six.bluecatshop.mapper.ActivityMapper;
import com.team.six.bluecatshop.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void add(Activity activity) {
        activityMapper.insert(activity);
    }

    @Override
    @Transactional
    public void remove(String id) {
        activityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Activity findById(String id) {
        Activity activity=activityMapper.selectByPrimaryKey(id);
        return activity;
    }

    @Override
    public List<Activity> findAll() {
        List<Activity> activityList = activityMapper.findAll();
        return activityList;
    }

    @Override
    public Activity findActivityByProductId(String id) {
        Activity activity = activityMapper.findByProductId(id);
        return activity;
    }


    @Override
    @Transactional
    public void updateByPrimaryKey(Activity activity) {
        activityMapper.updateByPrimaryKeySelective(activity);
    }

    public SeachActivityReponse findActivityAll(Integer pageNum, Integer pageSize, String keyword){
        PageHelper.startPage(pageNum,pageSize);
        ActivityExample example = new ActivityExample();
        example.createCriteria().andActivityDescribeLike("%"+ keyword + "%");
        List<Activity> activities = activityMapper.selectByExample(example);
        for (Activity activity : activities){
            if (activity.getProductId().equals("")){
                continue;
            }else {
                Product product = productMapper.selectByPrimaryKey(activity.getProductId());
                activity.setActivitytName(product.getProductName());
            }
        }
        return new SeachActivityReponse(((Page)activities).getTotal(),activities);
    }
}
